package com.lyj.cloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.core.MessageSource;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;

import com.lyj.cloud.business.Order;
import com.lyj.cloud.pipe.OrderProcessor;
import com.lyj.cloud.pipe.ProductProcessor;

@SpringBootApplication
@EnableBinding({Processor.class,OrderProcessor.class,ProductProcessor.class})
public class SpringCloudStreamApplication implements CommandLineRunner {

	@Autowired
    MessageChannel output;
	
    @Autowired
    @Qualifier("outputOrder")
    MessageChannel outputOrder;

//    @Autowired
//    ProductProcessor productProcessor;
    @Autowired
    @Qualifier("outputProductAdd")
    MessageChannel outputProduct;
    
	public static void main(String[] args) {
		SpringApplication.run(SpringCloudStreamApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		// TODO Auto-generated method stub
		// 字符串类型发送MQ
        System.out.println("字符串信息发送");
        output.send(MessageBuilder.withPayload("大家好").build());

        // 使用 定义的接口的方式来发送
        System.out.println("新增产品发送");
        outputProduct.send(MessageBuilder.withPayload("添加一个产品").build());
//        productProcessor.outputProductAdd().send(MessageBuilder.withPayload("添加一个产品").build());

        // 实体类型发送MQ
        System.out.println("订单实体发送");
        Order appleOrder = new Order();
        appleOrder.setOrderNum("0000001");
        appleOrder.setNum(10);
        appleOrder.setType("APPLE");
        appleOrder.setCreateAt(new java.util.Date());
        // 使用 注入 MessageChannel 方式发送
        outputOrder.send(MessageBuilder.withPayload(appleOrder).build());
	}
	
	// 定时轮询发送消息到 binding 为 Processor.OUTPUT
    @Bean
    @InboundChannelAdapter(value = Processor.OUTPUT, poller = @Poller(fixedDelay = "3000", maxMessagesPerPoll = "1"))
    public MessageSource<String> timerMessageSource() {
        return () -> MessageBuilder.withPayload("短消息-" + new java.util.Date()).build();
    }
    
}
